package com.ruoyi.livesass.api.sync;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.livesass.LiveVideoService;
import com.ruoyi.livesass.api.domain.LbsGkscDay;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.volcengine.model.livesaas.response.GetUserBehaviorListResponseAPIV2;
import com.volcengine.model.livesaas.response.GetUserBehaviorListResponseAPIV2.UserBehaviorV2;

import cn.hutool.core.lang.UUID;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@Component
@Order(100)
public class ExportZbjGksc {

	@Autowired
	LiveVideoService liveVideoService;

	@Autowired
	MemberMapper memberMapper;

	@Autowired
	SysDeptServiceImpl sysDeptServiceImpl;

	Map<Long, Member> memberCache;

	public List<LbsGkscDay> exportGkscToDay(long zbjid) {
		try {
			long activityId = zbjid;
			long pageNo = 1;
			long pageCount = 500;

			GetUserBehaviorListResponseAPIV2 apiResponse = liveVideoService.getUserBehaviorDataList(activityId, pageNo,
					pageCount);
			List<UserBehaviorV2> userList = apiResponse.getResult().getData();

			Map<String, LbsGkscDay> userGkscMap = Maps.newHashMap();

			processUserLiveTime(userList, userGkscMap);

			if (apiResponse.getResult().getTotalItemCount() > (pageNo * pageCount)) {// 代表一页取完数据
				long countItemSize = apiResponse.getResult().getTotalItemCount();
				long pageSize = (long) Math.ceil((double) countItemSize / pageCount);
				for (int i = 1; i < pageSize; i++) {
					pageNo++;
					long startTime = System.currentTimeMillis();

					apiResponse = liveVideoService.getUserBehaviorDataList(activityId, pageNo, pageCount);

					long endTime = System.currentTimeMillis();

					System.out.println("pageNo[" + pageNo + "],耗时[" + (endTime - startTime) + "]");

					userList = apiResponse.getResult().getData();
					processUserLiveTime(userList, userGkscMap);
				}
			}

			List<LbsGkscDay> lbsGkscDayList = Lists.newArrayList();

			for (String key : userGkscMap.keySet()) {
				lbsGkscDayList.add(userGkscMap.get(key));
			}

			Comparator<LbsGkscDay> ageComparator = Comparator
					.comparing(LbsGkscDay::getLivetime, Comparator.nullsLast(Comparator.naturalOrder())).reversed()
					.thenComparing(p -> p.getLivetime() == null ? 0 : p.getLivetime());

			lbsGkscDayList.sort(ageComparator);

			memberCache = null;
			return lbsGkscDayList;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	private void processUserLiveTime(List<UserBehaviorV2> userList, Map<String, LbsGkscDay> userGkscMap) {
		System.out.println("processUserLiveTime");
		for (UserBehaviorV2 userBehaviorItem : userList) {
			String userIdStr = userBehaviorItem.getExternalUserId();

			if (null == userIdStr || "".equals(userIdStr)) {
				continue;
			}

			LbsGkscDay lbsGkscday = null;
			if (userGkscMap.containsKey(userIdStr)) {
				lbsGkscday = userGkscMap.get(userIdStr);
			} else {
				long wcUserId = Long.valueOf(userIdStr);
				Member member = getMember(wcUserId);
				if (null == member) { // 没有找到对应的会员
					continue;
				}
				lbsGkscday = initLbsGkscDay(member, wcUserId);
				lbsGkscday.setLivetime(0);
				userGkscMap.put(userIdStr, lbsGkscday);
			}

			Integer reLiveTime = lbsGkscday.getLivetime();

			if (null == reLiveTime) {
				reLiveTime = new Integer(0);
			}

			// Long sumTime = (reLiveTime + userBehaviorItem.getWatchTime());
			lbsGkscday.setLivetime(userBehaviorItem.getWatchTime().intValue());

		}

	}

	private LbsGkscDay initLbsGkscDay(Member member, long wcUserId) {
		LbsGkscDay lbsGkscday = new LbsGkscDay();
		lbsGkscday.setDeptTzId(member.getDeptTzId());
		lbsGkscday.setDeptZbjId(member.getDeptZbjId());

		lbsGkscday.setDeptDpId(member.getDeptDpId());
		SysDept sysDept = sysDeptServiceImpl.getCacheSysDept(member.getDeptDpId());
		if (null != sysDept) {
			lbsGkscday.setDeptDpName(sysDept.getDeptName());
		}

		lbsGkscday.setWcUserId(wcUserId);
		lbsGkscday.setAvatar(member.getAvatar());
		lbsGkscday.setNickname(member.getNickname());
		return lbsGkscday;
	}

	private Member getMember(long wcUserId) {
		if (null == memberCache) {
			memberCache = Maps.newHashMap();
			QueryWrapper<Member> qw = new QueryWrapper<>();
			List<Member> memberList = memberMapper.selectList(qw);
			for (Member item : memberList) {
				memberCache.put(item.getId(), item);
			}
		}

		return memberCache.get(wcUserId);
	}
}
